package com.swordliu.facebook.controller;

import com.swordliu.facebook.Utils.SingleLoginUtil;
import com.swordliu.facebook.controller.base.BaseController;
import com.swordliu.facebook.pojo.entity.User;
import com.swordliu.facebook.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * login
 * Created by SwordLiu on 2017-07-03.
 */
@Controller
public class LoginController extends BaseController {

    @Resource
    private UserService userService;

    @RequestMapping("/login.html")
    public String loginPage() {

        return "login";
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public String login(User login, Boolean rememberme, Model model, HttpServletRequest request) {

        //生成验证的token
        UsernamePasswordToken token = new UsernamePasswordToken(login.getUsername(), login.getPassword());

        Subject currentUser = SecurityUtils.getSubject();
        //设置记住我
        token.setRememberMe(true);
        try {
            //使用shiro做登录验证，并授权
            currentUser.login(token);
        } catch (AuthenticationException e) {
            return "redirect:login.html";
        }

        if (currentUser.isAuthenticated()) {

            SingleLoginUtil.login(request.getSession(), login.getUsername());

            return "redirect:index.html";
        }

        return "redirect:login.html";
    }

    @RequestMapping(value = "/regist.do", method = RequestMethod.POST)
    @ResponseBody
    public Integer regist(User regist) throws Exception{
        Integer val = 0;
        try {
            val = userService.regist(regist);
        } catch (Exception e) {
            return -1;
        }
        return val;
    }

    @RequestMapping(value = "/logout.do", method = RequestMethod.POST)
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:login.html";
    }

    @RequestMapping("index.html")
    public String toIndex() throws Exception {
        return "index";
    }

}
